/*
 * 刷新间隔(20分钟)
 */
var REFRESH_TIME = 120000;
/**
 * 定位操作
 */
var LocationUtil = {};
/**
 * 地球长轴(单位M)
 * @type {number}
 */
var EARTH_RADIUS = 6378137.0;
/**
 * π
 * @type {number}
 */
var PI = Math.PI;
/**
 * 角度转弧度
 * @param {Number} d 角度
 * @returns {Number} 弧度
 */
var getRad = function (d) {
    return d * PI / 180.0;
};
/**
 * 开始刷新地址
 * @public
 */
LocationUtil.startRefreshAddress = function () {
    if (window.inReview) {
        return;
    }
    LocationUtil.refreshAddress();
    cc.log('开始刷新地址');
    setTimeout(LocationUtil.startRefreshAddress, REFRESH_TIME);
};

/**
 * 刷新地址
 * @private
 */
LocationUtil.refreshAddress = function () {
    if (!cc.sys.isNative) {
        return;
    }
    LocationUtil.address = null;
    if (cc.sys.os === cc.sys.OS_IOS && window.nativeVersion >= app.framework_version) {
        LocationManager.requestLocation();
    } else {
        LocationUtil.start();
    }
};


/**
 * 开始
 */
LocationUtil.init = function () {
    if (window.inReview) {
        return;
    }
    if (window.fristIn && !PermissionUtil.hasPermission(PermissionType.Location)) {
        PermissionUtil.requestPermission(PermissionType.Location);
    }
};
/**
 * 开始监听
 */
LocationUtil.start = function () {
    LocationUtil.fristStart = true;
    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod("LocationUtil", "start");
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        jsb.reflection.callStaticMethod(packageUri + "/utils/LocationUtil", "start", "()V");
    }
};
/**
 * 停止监听
 */
LocationUtil.stop = function () {
    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod("LocationUtil", "stop");
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        jsb.reflection.callStaticMethod(packageUri + "/utils/LocationUtil", "stop", "()V");
    }
};
/**
 * 取得具体地点
 * @param {String}locStr
 * @param {String}infoStr
 */
LocationUtil.getLocationInfo = function (locStr, infoStr) {
    if (isNullString(locStr)) {
        return;
    }
    if (!LocationUtil.fristStart) {
        return;
    }
    gameData.location = locStr;
    var coordtype = 'wgs84ll';
    if (cc.sys.os == cc.sys.OS_ANDROID) {
        if (!isNullString(infoStr)) {
            cc.log('请求地址信息成功!' + locStr + infoStr);
            gameData.locationInfo = infoStr;
            var sendData = {};
            sendData.location = gameData.location;
            sendData.locationCN = gameData.locationInfo;
            LocationUtil.address = infoStr;
            network.send(MsgCode.RefreshPlayersLoc, sendData);
            return;
        }
        coordtype = 'bd09ll';
        LocationUtil.stop();
    }
    if (LocationUtil.requestInterval) {
        clearInterval(LocationUtil.requestInterval);
        LocationUtil.requestInterval = null;
    }
    LocationUtil.requestInterval = setInterval(LocationUtil.requestBaidu.bind(this, coordtype, locStr), 100);

};

/**
 * 发送百度地址请求
 * @param coordtype
 * @param locStr
 */
LocationUtil.requestBaidu = function (coordtype, locStr) {
    if (LocationUtil.requestInterval) {
        clearInterval(LocationUtil.requestInterval);
        LocationUtil.requestInterval = null;
    }
    LocationUtil.fristStart = false;
    var url = 'http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&coordtype=' + coordtype + '&location=' + locStr + '&output=json&pois=0&ak=' + LocationUtil.randomKey();
    http.get(url,
        function (str) {
            try {
                str = str.substring(29, str.length - 1);
                var jsonData = JSON.parse(str);
                var status = jsonData.status;
                if (status == 0) {
                    var locationInfo = jsonData.result['formatted_address'];
                    var lng = jsonData.result.location['lng']; //经度 北京116.46
                    var lat = jsonData.result.location['lat']; //纬度 北京39.92
                    if (lng)
                        gameData.location = lat + ',' + lng;
                    if (!isNullString(locationInfo)) {
                        cc.log('请求地址信息成功!');
                        gameData.locationInfo = locationInfo;
                        var sendData = {};
                        sendData.location = gameData.location;
                        sendData.locationCN = gameData.locationInfo;
                        LocationUtil.address = locationInfo;
                        network.send(MsgCode.RefreshPlayersLoc, sendData);
                    }
                    // cc.log(gameData.location);
                    // cc.log(gameData.locationInfo);
                }

            }
            catch (e) {

            }
            ;

        },
        function () {
        },
        {'Accept-Encoding': 'deflate'}
    );
};

LocationUtil.randomKey = function () {
    var id = Math.round(Math.random() * 3);
    var KEYS = [
        'WIVhGkuCRHrD57PnqK3hqZYpMjgavx9p',
        'Y8XAbnM0mhXYURWjX7EUer999wONTdRl',
        'haB8XTt53xh5uIZoAwEhYAAZVUrLhDWy',
        'NKOlWy6PxCWBXyoxT93LZhAVvw7UkPFZ'
    ];
    if (id < 0 || id >= KEYS.length) {
        id = 0;
    }
    return KEYS[id];
};

/**
 * approx distance between two points on earth ellipsoid
 * @param lat1
 * @param lng1
 * @param lat2
 * @param lng2
 * @returns {Number} distance
 */
LocationUtil.getFlatternDistance = function (lat1, lng1, lat2, lng2) {
    lat1 = parseFloat(lat1);
    lng1 = parseFloat(lng1);
    lat2 = parseFloat(lat2);
    lng2 = parseFloat(lng2);
    var f = getRad((lat1 + lat2) / 2);
    var g = getRad((lat1 - lat2) / 2);
    var l = getRad((lng1 - lng2) / 2);

    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s, c, w, r, d, h1, h2;
    var a = EARTH_RADIUS;
    var fl = 1 / 298.257;

    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;

    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;

    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;

    var ret = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
    return _.isNaN(ret) ? 0 : ret.toFixed(1);
};

LocationUtil.getIpLocation = function (ip) {
    var url = 'http://api.map.baidu.com/location/ip?ak=WgKT6s5sSVSYclt3kKWzllUnXrGgMd49&ip=' + ip + '&coor=bd09ll';
    http.get(url, function (data) {
        var json = JSON.parse(data);
        var lng = json.content.point.x; //经度 北京116.46
        var lat = json.content.point.y; //纬度 北京39.92
        if (lng)
            gameData.location = lat + ',' + lng;
        if (!isNullString(json.content.address)) {
            cc.log('请求地址信息成功!');
            gameData.locationInfo = json.content.address;
            var sendData = {};
            sendData.location = gameData.location;
            sendData.locationCN = gameData.locationInfo;
            LocationUtil.address = gameData.locationInfo;
            network.send(MsgCode.RefreshPlayersLoc, sendData);
        }
    }, function () {
        // cc.log("查找失败");
    });
};